/*
 * Copyright 2005-2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jfrog.jade.plugins.common.uptodate;

import org.apache.maven.project.MavenProject;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.UpToDate;
import org.apache.tools.ant.types.FileSet;
import org.jfrog.jade.components.uptodate.UpToDateAnalyzer;
import org.jfrog.jade.plugins.common.injectable.MvnInjectable;

import java.io.File;

/**
 * User: freds
 * Date: Aug 5, 2007
 * Time: 9:46:13 AM
 */
public class UpToDateAnalyzerImpl implements UpToDateAnalyzer {
    private final Project antProject;
    private final MavenProject mavenProject;

    public UpToDateAnalyzerImpl(MvnInjectable injectable) {
        mavenProject = injectable.getProject();
        antProject = injectable.getMaven2AntManager().getAntProject(injectable);
    }

    public boolean isUpToDate(File dest, File src) {
        if (src == null || !src.exists()) {
            throw new RuntimeException("File " + src + " not found when trying to test for Up To Date of " + dest);
        }

        //quick compare  with the source where the user likely to change first
        if (dest == null || !dest.exists() ||
                (dest.lastModified() < src.lastModified())) {
            return false;
        }

        if (src.isDirectory()) {
            FileSet fileSet = new FileSet();
            fileSet.setProject(antProject);
            fileSet.setDir(src);
            fileSet.setExcludes(".svn CVS");

            UpToDate upToDate = new UpToDate();
            upToDate.setProject(antProject);
            upToDate.setTargetFile(dest);
            upToDate.addSrcfiles(fileSet);

            return upToDate.eval();
        } else {
            return true;
        }
    }
}
